package com.ming.reentrantLock;

import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Auther: tangC
 * @Date: 2020/7/9 13:56
 * @Description:
 */

@Slf4j
public class ReentrantLockDemo implements Runnable{

    // 读写锁
    private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    // 参数true 表示公平锁
    private static ReentrantLock reentrantLock = new ReentrantLock(true);
    @Override
    public void run() {
        try {
            if (Thread.currentThread().getName().contains("read")){
                read();
            }else {
                write();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {

        }
    }


    public void read(){
        log.info("线程{}进入:{}",Thread.currentThread().getName(),new SimpleDateFormat("hh:mm:ss").format(new Date()));
        try {
            lock.readLock().lock();
            log.info("{}获取了读锁:{}",Thread.currentThread().getName(),new SimpleDateFormat("hh:mm:ss").format(new Date()));
            Thread.sleep(3000);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.readLock().unlock();
            log.info("{}释放了读锁:{}",Thread.currentThread().getName(),new SimpleDateFormat("hh:mm:ss").format(new Date()));
        }
    }


    public void write(){
        log.info("线程{}进入:{}",Thread.currentThread().getName(),new SimpleDateFormat("hh:mm:ss").format(new Date()));
        try {
            lock.writeLock().lock();
            log.info("{}获取了写锁:{}",Thread.currentThread().getName(),new SimpleDateFormat("hh:mm:ss").format(new Date()));
            Thread.sleep(3000);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.writeLock().unlock();
            log.info("{}释放了写锁:{}",Thread.currentThread().getName(),new SimpleDateFormat("hh:mm:ss").format(new Date()));
        }
    }
}
